package com.eveinfo.widget;

import java.util.ArrayList;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.sqlite.SQLiteException;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;
import android.widget.RemoteViews;

import com.eveinfo.R;
import com.eveinfo.api.ApiAuthorization;
import com.eveinfo.api.character.skilltraining.ApiSkillTraining;
import com.eveinfo.api.character.skilltraining.SkillTrainingParser;
import com.eveinfo.sql.DataBaseHelper;
import com.eveinfo.tools.ConfigFileException;
import com.eveinfo.tools.Pilot;
import com.eveinfo.tools.Setting;
import com.eveinfo.tools.Tools;

public class WidgetService extends Service {

	private static final String TAG = "WidgetService";

	private ArrayList<Pilot> pilots;
	volatile static private int current = 0;
	private Pilot pilot;
	private ApiSkillTraining training;
	private BitmapDrawable bitmap;

	private static String UPDATE = "UPDATE";

	@Override
	public void onCreate() {
		super.onCreate();
		Log.d(TAG, "onCreate");
		try {
			pilots = Setting.readOptions(this);

			RemoteViews updateViews = new RemoteViews(this.getPackageName(), R.layout.appwidget_provider);
			Intent updateIntent = new Intent(UPDATE);
			PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, updateIntent,
					PendingIntent.FLAG_UPDATE_CURRENT);
			updateViews.setOnClickPendingIntent(R.id.IVWidgetPicture, pendingIntent);

			registerReceiver(new BroadcastReceiver() {
				@Override
				public void onReceive(Context context, Intent intent) {
					current++;
					if (current == pilots.size()) {
						current = 0;
					}
					initPilot();
				}
			}, new IntentFilter(UPDATE));

			ComponentName thisWidget = new ComponentName(this, WidgetProvider.class);
			AppWidgetManager manager = AppWidgetManager.getInstance(this);
			manager.updateAppWidget(thisWidget, updateViews);

			initPilot();
		} catch (ConfigFileException e) {
			final Intent intent = new Intent();
			intent.setAction(AppWidgetManager.ACTION_APPWIDGET_DELETED);
			PendingIntent newPending = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
			AlarmManager alarms = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
			alarms.set(AlarmManager.ELAPSED_REALTIME, 0, newPending);
			stopSelf();
			e.printStackTrace();
		}
	}

	private void initPilot() {
		try {
			pilot = pilots.get(current);
			SkillTrainingParser parser = SkillTrainingParser.getInstance();
			training = parser.getSkillInTraining(new ApiAuthorization(pilot.getUserId(), pilot.getCharacterId(), pilot
					.getApiKey()));
			bitmap = new BitmapDrawable(Tools.getCharacterImageBitmap(pilot.getCharacterId(), false));
			int appWidgetId = 0;
			Intent widgetUpdate = new Intent();
			widgetUpdate.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
			widgetUpdate.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { appWidgetId });
			widgetUpdate.setData(Uri.withAppendedPath(Uri.parse(WidgetProvider.URI_SCHEME + "://widget/id/"), String
					.valueOf(appWidgetId)));
			PendingIntent newPending = PendingIntent.getBroadcast(this, 0, widgetUpdate,
					PendingIntent.FLAG_UPDATE_CURRENT);
			AlarmManager alarms = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
			alarms.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), newPending);

		} catch (Exception e) {
			final Intent intent = new Intent();
			intent.setAction(AppWidgetManager.ACTION_APPWIDGET_DELETED);
			PendingIntent newPending = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
			AlarmManager alarms = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
			alarms.set(AlarmManager.ELAPSED_REALTIME, 0, newPending);
			stopSelf();
			e.printStackTrace();
		}
	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		Log.d(TAG, "onStart");

		RemoteViews updateViews = new RemoteViews(this.getPackageName(), R.layout.appwidget_provider);

		updateViews.setImageViewBitmap(R.id.IVWidgetPicture, bitmap.getBitmap());
		updateViews.setTextViewText(R.id.TVWidgetName, pilot.getName());
		if (training.isSkillInTraining()) {
			DataBaseHelper dataBaseHelper = new DataBaseHelper(this);
			String typeName = "";
			try {
				dataBaseHelper.openDataBase();
				typeName = dataBaseHelper.getTypeName(training.getTrainingTypeID());
				dataBaseHelper.close();
			} catch (SQLiteException e) {
				typeName = "no database";
			}
			updateViews.setTextViewText(R.id.TVWidgetSkill, typeName + " lvl" + training.getTrainingToLevel());
			updateViews.setTextViewText(R.id.TVWidgetTraining, Tools.convertTime(training.getRemainTime(), false));
		} else {
			updateViews.setTextViewText(R.id.TVWidgetSkill, "No skill");
			updateViews.setTextViewText(R.id.TVWidgetTraining, "");
		}
		ComponentName thisWidget = new ComponentName(this, WidgetProvider.class);
		AppWidgetManager manager = AppWidgetManager.getInstance(this);
		manager.updateAppWidget(thisWidget, updateViews);

	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

}
